Skip to content

Fix FP arrayIndexOutOfBounds for a for loop whose condition changes in its body - #9110

Open
APX403 wants to merge 1 commit into
cppcheck-opensource:mainfrom
APX403:fix-forloop-cond-in-body
Open

APX403 wants to merge 1 commit into
cppcheck-opensource:mainfrom
APX403:fix-forloop-cond-in-body

Conversation

@APX403

@APX403 APX403 commented Dec 3, 2026

Copy link
Copy Markdown

arrayIndexOutOfBounds reports index 9998 for a for loop whose condition only changes in its body:

int f(void) {
    const char s[] = "abc";
    int n = 0;
    for (int i = 0, done = 0; done == 0; i++) {
        if (s[i] == '\0')
            done = 1;
        else
            n++;
    }
    return n;
}
loop.c:5:14: error: Array 's[4]' accessed at index 9998, which is out of bounds. [arrayIndexOutOfBounds]

valueFlowForLoop2() runs the three expressions of the loop header without the body, so done == 0 stays true until maxForLoopCount is reached, and the memory of the last pass is then used as the last iteration, which puts 9998 into i in the body. Since #8899 the state after the loop is not used when the limit is reached; when the body changes the condition, the last iteration is not known either. An endless loop such as for (int n = 0; 1; ++n) still reports index 9998, as the test for ticket 13109 expects.

raylib's raygui.h splits the item texts of GuiToggleGroup() with such a loop (raygui.h#L2189), which showed up in the package run of #9078.

I don't have a Trac account, so I couldn't create a ticket for this.

@dmcppcheck

Copy link
Copy Markdown
Contributor

There should probably be a trac ticket for this PR. Please create it, or ask us to create it. Then the PR title should be updated.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The change removes the 9998 FP from the example in the description, and the tests pass. Two closely related forms of the same loop still give a false positive:

  1. A flag set at the last valid index: if (i == 9) done = 1; with a[10]. Base reported index 9998. The PR now reports arrayIndexOutOfBoundsCond at index 10, which is still wrong: i == 9 ends the loop, so i never reaches 10. The value 10 already existed in base, where the 9998 error at the same spot hid it.
  2. A flag combined with a bound in the condition: !done && i < 100. The condition becomes false within the iteration limit (result == 0), so the last iteration is still taken from the header only, even though the body changes done. Index 99 is reported for s[4], as in base.

So the reasoning that the last iteration is unknown when the body changes the condition is only applied when the limit is reached. I found no crash, hang or new kind of false positive.

Comments

# Comment By Where Status
1 PR should have a trac ticket and the title should reference it @dmcppcheck general ⚠️ Open
2 Last iteration still taken from the header when the condition ends in time but the body changes it (!done && i < 100) AI review lib/valueflow.cpp:5305 🆕 New
3 Same pattern with the flag set at the last valid index still gives an FP (arrayIndexOutOfBoundsCond index 10) AI review test/testbufferoverrun.cpp:2723 🆕 New

@APX403, please fix, resolve or reply to the open and new comments: #1, #2, #3.

Testing

I built cppcheck and testrunner in pr/ and cppcheck in base/.

./testrunner TestBufferOverrun TestValueFlow TestUninitVar TestNullPointer TestCondition TestOther: 846 tests, 0 failures.

The example in the PR description: base reports index 9998, the PR reports nothing. An endless loop without a flag still reports 9998.

Remaining false positives (/work/{base,pr}/cppcheck -q --enable=warning b.c):

void g1(void) {
    int a[10];
    for (int i = 0, done = 0; done == 0; i++) {
        a[i] = 0;
        if (i == 9) done = 1;
    }
}
int g3(void) {
    const char s[] = "abc";
    int n = 0;
    for (int i = 0, done = 0; !done && i < 100; i++) {
        if (s[i] == '\0') done = 1; else n++;
    }
    return n;
}

base:

b.c:4:10: error: Array 'a[10]' accessed at index 9998, which is out of bounds. [arrayIndexOutOfBounds]
b.c:11:14: error: Array 's[4]' accessed at index 99, which is out of bounds. [arrayIndexOutOfBounds]

pr:

b.c:4:10: warning: Either the condition 'i==9' is redundant or the array 'a[10]' is accessed at index 10, which is out of bounds. [arrayIndexOutOfBoundsCond]
b.c:11:14: error: Array 's[4]' accessed at index 99, which is out of bounds. [arrayIndexOutOfBounds]

In both cases the code is safe:

  • In g1, --debug shows that i has the possible value 10 in base too (i possible {9,10,0,9998}); only 9998 is gone in the PR.
  • In g3, the loop stops at i == 3.

Automated review of bec10bb by Claude. The pull request was built and tested locally.

Comment thread lib/valueflow.cpp
// When the limit of iterations was reached because only the loop body changes the condition,
// the last iteration is not known either
const Token* bodyStart = tok->linkAt(1)->next();
if (result == 0 || !findExpressionChanged(secondExpression, bodyStart, bodyStart->link(), settings))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The check is skipped when result == 0, but the comment's reasoning applies there too: if the body changes the condition, the loop can end before the header-only simulation does. Example:

const char s[] = "abc";
for (int i = 0, done = 0; !done && i < 100; i++) {
    if (s[i] == '\0') done = 1;
}

This still gives Array 's[4]' accessed at index 99 (same as base). Dropping memory2 whenever findExpressionChanged(secondExpression, ...) is true, whatever result is, would also cover this case. memoryAfter could still be kept when result == 0.

" }\n"
" return n;\n"
"}\n");
ASSERT_EQUALS("", errout_str());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

A variant of the new test is still reported:

void g1(void) {
    int a[10];
    for (int i = 0, done = 0; done == 0; i++) {
        a[i] = 0;
        if (i == 9) done = 1;
    }
}

The PR reports Either the condition 'i==9' is redundant or the array 'a[10]' is accessed at index 10 (base reported index 9998 instead). i == 9 ends the loop, so 10 is never used as an index. The value comes from forwarding i==9 through i++ back into the body, ignoring that done = 1 ends the loop. In base it was hidden behind the 9998 error. Please consider adding this case, at least as a TODO assert.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants